//EditorPage_1.js文件主要作用于问卷编辑页（editor.html）

// 1- 全局变量
//测试代码：
//createQuestionnaireBtn();
var Questionnaire = JSON.parse(
  localStorage.getItem("currentOperatedQuestionnaire")
);
questionFresh();
//2-操作问卷对象 —— 给问卷对象生成展示页面:
function addQuestion() {
  let typeOfQuestion = document.getElementById("typeOfQuestion");
  typeOfQuestion.innerHTML = '<input type="button" onclick="createSingleChoice()" class = "single" /><input type="button" onclick="createMultipleChoice()" class = "multiple" /><input type="button" onclick="createTextChoice()" class = "text" />';
}
//2-1 创建单选题
function createSingleChoice() {
  let content = document.getElementById("questionnaire_content");
  let div = document.createElement("div");
  div.className = "choice";
  let p = document.createElement("p");
  let questionOrder =
    document.getElementById("questionnaire_content").children.length + 1;
  //创建题目标题输入框 (ing)!!!!!!!!!!!
  let titleInput = document.createElement("input");
  titleInput.type = "text";
  // p.appendChild(titleInput);
  p.innerText = "Q" + questionOrder + "（单选题）：";
  let BR = document.createElement("br");
  div.setAttribute("type", "single"); //将该问题标注为 type = single
  div.appendChild(p);
  div.appendChild(titleInput);
  div.appendChild(BR);
  //是题目输入框不要和选项在同一行，美化后可删除

  for (let i = 1; i <= 2; i++) {
    let label = document.createElement("label");

    let inputOuter = document.createElement("input");
    inputOuter.type = "radio";
    //inputOuter.name = "answer" + order; // 单选，所有选项的name必须相同，以实现只选一个选项的效果
    inputOuter.name = "answer" + questionOrder; //???????测试代码
    //inputOuter.id = order + "_checkradio_" + i; // 第order题的第i个选项
    inputOuter.value = i;

    let inputInner = document.createElement("input");
    inputInner.type = "text";
    //inputInner.id = inputOuter.id + "_text";
    inputInner.placeholder = "选项" + i;

    let br = document.createElement("br");
    label.appendChild(inputOuter);
    label.appendChild(inputInner);
    div.appendChild(label);
    div.appendChild(br);
  }

  let newDiv = addOperateBtns(questionOrder, div); //给div添加四个按键后返回新的div
  content.appendChild(newDiv);

  return newDiv;
}

//2-2 创建双选题
function createMultipleChoice() {
  let content = document.getElementById("questionnaire_content");
  let div = document.createElement("div");
  let p = document.createElement("p");
  div.className = "choice";
  //创建题目标题输入框 (ing)!!!!!!!!!!!
  let titleInput = document.createElement("input");
  titleInput.type = "text";

  let questionOrder =
    document.getElementById("questionnaire_content").children.length + 1;
  //p.innerText = "Q" + questionOrder+"    " + "双选题：";
  p.innerText = "Q" + questionOrder + "（多选题）：";

  div.setAttribute("type", "multiple");
  div.appendChild(p);
  div.appendChild(titleInput);
  let BR = document.createElement("br");
  div.appendChild(BR);

  for (let i = 1; i <= 4; i++) {
    let label = document.createElement("label");
    let inputX = document.createElement("input");
    let inputY = document.createElement("input");
    let span = document.createElement("span");
    let br = document.createElement("br");

    //选项点击处
    inputX.type = "checkbox";
    inputX.name = "answer";
    inputX.value = i;
    //inputX.id = order + "_checkbox_" + i; //第order题的第i个选项
    //选项内容
    inputY.type = "text";
    inputY.placeholder = "选项" + i;
    //inputY.id = inputX.id + "_text";

    label.appendChild(inputX);
    label.appendChild(inputY);
    div.appendChild(label);
    div.appendChild(br);
  }

  let newDiv = addOperateBtns(questionOrder, div); //给div添加四个按键后返回新的div
  content.appendChild(newDiv);

  return newDiv;
}

//2-3 创建文本题
function createTextChoice() {
  // 编写代码
  let content = document.getElementById("questionnaire_content");
  let div = document.createElement("div");
  div.className = "choice";
  //div.id = order;
  div.setAttribute("type", "text");
  let p = document.createElement("p");
  //创建题目标题输入框 (ing)!!!!!!!!!!!
  let titleInput = document.createElement("input");
  titleInput.type = "text";

  let questionOrder =
    document.getElementById("questionnaire_content").children.length + 1;
  p.innerText = p.innerText = "Q" + questionOrder + "（文本题）：";
  let input = document.createElement("input");
  input.className="textinput";
  input.type = "text";

  div.appendChild(p);
  div.appendChild(titleInput);
  let BR = document.createElement("br");
  div.appendChild(BR);
  div.appendChild(input);

  let newDiv = addOperateBtns(questionOrder, div); //给div添加四个按键后返回新的div
  content.appendChild(newDiv);

  return newDiv;
}

//2-4 创建 delete、upMove、downMove、repeat四个按键
function addOperateBtns(questionOrder, div) {
  //questionOrder - 题号 ； div - 题号对应题目
  let deleteBtn = document.createElement("input"); //删除按键
  deleteBtn.className = "deletebtn";
  deleteBtn.type = "button";
  deleteBtn.value = "删除";
  deleteBtn.setAttribute("qnumber", questionOrder);
  deleteBtn.name = "delete";
  deleteBtn.setAttribute(
    "onclick",
    'javascript:deleteQuestion(this.getAttribute("qnumber"))'
  );
  div.appendChild(deleteBtn);

  let upMoveBtn = document.createElement("input"); //上移按键
  upMoveBtn.className = "upmovebtn";
  upMoveBtn.type = "button";
  upMoveBtn.value = "上移";
  upMoveBtn.name = "upmove";
  upMoveBtn.setAttribute("qnumber", questionOrder);
  upMoveBtn.setAttribute(
    "onclick",
    'javascript:upMoveQuestion(this.getAttribute("qnumber"))'
  );
  div.appendChild(upMoveBtn);

  let downMoveBtn = document.createElement("input"); //下移按键
  downMoveBtn.className = "downmovebtn";
  downMoveBtn.type = "button";
  downMoveBtn.value = "下移";
  downMoveBtn.name = "upmove";
  downMoveBtn.setAttribute("qnumber", questionOrder);
  downMoveBtn.setAttribute(
    "onclick",
    'javascript:downMoveQuestion(this.getAttribute("qnumber"))'
  );
  div.appendChild(downMoveBtn);

  let repeatUseBtn = document.createElement("input"); //复用按键
  repeatUseBtn.className = "repeatusebtn";
  repeatUseBtn.type = "button";
  repeatUseBtn.value = "复用";
  repeatUseBtn.name = "repeat";
  repeatUseBtn.setAttribute("qnumber", questionOrder);
  repeatUseBtn.setAttribute(
    "onclick",
    'javascript:repeatUseBtn(this.getAttribute("qnumber"))'
  );
  div.appendChild(repeatUseBtn);

  return div;
}

// //3 - 操作问卷对象 —— 保存问卷对象中选中的、输入的数据信息
// //删除题目    --------------------   （要考虑到编辑过程中，出题又删题的情况)
function deleteQuestion(n) {
  //删除题号为n的题
  console.log("测试：deleteQuestion()（执行SaveData_btn()前） >> ");
  SaveData_btn();
  let questionnaire_content = document.getElementById("questionnaire_content");
  //删除指定问题
  console.log("测试：deleteQuestion() （执行SaveData_btn()后）>>");
  console.log(
    "删除之前HTML: questionnaire_content.children[n-1] = " +
    questionnaire_content.children[n - 1]
  );
  questionnaire_content.removeChild(questionnaire_content.children[n - 1]);
  console.log(
    "删除之后HTML: questionnaire_content.children[n-1] = " +
    questionnaire_content.children[n - 1]
  );
  //取出并删除localStorage中问卷数组中的对应的数据
  let curQuestionnaire = JSON.parse(
    localStorage.getItem("currentOperatedQuestionnaire")
  );
  console.log(
    "当前操作问卷对象currentOperatedQuestionnaire = " + curQuestionnaire
  );
  console.log(
    "当前操作问卷对象在问卷数组中的下标 indexOfCurrentOperatedQuestionnaire = " +
    JSON.parse(localStorage.getItem("indexOfcurrentOperatedQuestionnaire"))
  );
  console.log(
    "删除localStorage中数据之前，curQuestionnaire.questions[].length = " +
    curQuestionnaire.questions.length
  );
  console.log(
    "删除localStorage中数据之前，curQuestionnaire.questions[n-1] = " +
    curQuestionnaire.questions[n - 1]
  );
  curQuestionnaire.questions.splice(n - 1, 1); //n-1 : n是题号，所以(n-1)是下标
  localStorage.setItem(
    "currentOperatedQuestionnaire",
    JSON.stringify(curQuestionnaire)
  );
  let questionnaires = JSON.parse(localStorage.getItem("Questionnaires"));
  let indexOfCurQuestionnaire = localStorage.getItem(
    "indexOfcurrentOperatedQuestionnaire"
  );
  console.log(
    "locaStorage中取出的indexOfCurrentOperatedQuestionnaire = " +
    indexOfCurQuestionnaire
  );
  questionnaires[indexOfCurQuestionnaire] = curQuestionnaire;
  localStorage.setItem("Questionnaires", JSON.stringify(questionnaires));
  questionFresh();
}

//上移函数
function upMoveQuestion(n) {
  // 当前的题号
  SaveData_btn();
  let questionnaire_content = document.getElementById("questionnaire_content");
  //上移问题：将当前问题的位置和上一个问题的位置进行调整
  if (n == 1) {
    //判断当前问题是否已经是第一题
    //fresh();
    questionFresh();
    return;
  }
  let temp = questionnaire_content.children[n - 2]; //当前位置 n-1 ,上一位置 n-2
  questionnaire_content.children[n - 2] = questionnaire_content.children[n - 1];
  questionnaire_content.children[n - 1] = temp;
  //问题的数据也要调整保存位置
  let curOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("currentOperatedQuestionnaire")
  );
  temp = curOperatedQuestionnaire.questions[n - 2];
  curOperatedQuestionnaire.questions[n - 2] =
    curOperatedQuestionnaire.questions[n - 1];
  curOperatedQuestionnaire.questions[n - 1] = temp;
  localStorage.setItem(
    "currentOperatedQuestionnaire",
    JSON.stringify(curOperatedQuestionnaire)
  );
  let questionnaires = JSON.parse(localStorage.getItem("Questionnaires"));
  let indexOfCurrentOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("indexOfcurrentOperatedQuestionnaire")
  );
  questionnaires[indexOfCurrentOperatedQuestionnaire] =
    curOperatedQuestionnaire;
  localStorage.setItem("Questionnaires", JSON.stringify(questionnaires));
  questionFresh();
}

//下移函数
function downMoveQuestion(n) {
  // 当前的题号
  SaveData_btn();
  let questionnaire_content = document.getElementById("questionnaire_content");
  //下移问题：将当前问题的位置和下一个问题的位置进行调整
  if (n == questionnaire_content.children.length) {
    //判断当前问题是否已经是最后一题
    return;
  }
  let temp = questionnaire_content.children[n]; //当前位置n-1 , 下一位置n
  questionnaire_content.children[n] = questionnaire_content.children[n - 1];
  questionnaire_content.children[n - 1] = temp;
  //问题的数据也要调整保存位置
  let curOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("currentOperatedQuestionnaire")
  );
  temp = curOperatedQuestionnaire.questions[n];
  curOperatedQuestionnaire.questions[n] =
    curOperatedQuestionnaire.questions[n - 1];
  curOperatedQuestionnaire.questions[n - 1] = temp;
  localStorage.setItem(
    "currentOperatedQuestionnaire",
    JSON.stringify(curOperatedQuestionnaire)
  );
  let questionnaires = JSON.parse(localStorage.getItem("Questionnaires"));
  let indexOfCurrentOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("indexOfcurrentOperatedQuestionnaire")
  );
  questionnaires[indexOfCurrentOperatedQuestionnaire] =
    curOperatedQuestionnaire;
  localStorage.setItem("Questionnaires", JSON.stringify(questionnaires));
  questionFresh();
}

//复用函数
function repeatUseBtn(n) {
  SaveData_btn();
  let questionnaire_content = document.getElementById("questionnaire_content");
  //复制当前问题
  let copy = document.getElementById("questionnaire_content").children[n - 1];
  questionnaire_content.insertBefore(
    copy,
    document.getElementById("questionnaire_content").children[n - 1]
  );
  //问题的数据也要调整保存位置
  let curOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("currentOperatedQuestionnaire")
  );
  copy = curOperatedQuestionnaire.questions[n - 1];
  curOperatedQuestionnaire.questions.splice(n, 0, copy);
  localStorage.setItem(
    "currentOperatedQuestionnaire",
    JSON.stringify(curOperatedQuestionnaire)
  );

  let questionnaires = JSON.parse(localStorage.getItem("Questionnaires"));
  let indexOfCurrentOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("indexOfcurrentOperatedQuestionnaire")
  );
  questionnaires[indexOfCurrentOperatedQuestionnaire] =
    curOperatedQuestionnaire;
  localStorage.setItem("Questionnaires", JSON.stringify(questionnaires));
  questionFresh();
}

//questionFresh刷新页面题号的函数
function questionFresh() {
  console.log("测试：questionFresh() >>");

  document.getElementById("questionnaire_content").innerHTML = "";

  let currentOperatedQuestionnaire = JSON.parse(
    localStorage.getItem("currentOperatedQuestionnaire")
  );
  console.log(
    "localStorage中取出当前问卷操作对象currentOperatedQuestionnaire = " +
    currentOperatedQuestionnaire
  );
  console.log(
    "从localStorage中取出 indexOfCurrentOperatedQuestionnaire = " +
    JSON.parse(localStorage.getItem("indexOfcurrentOperatedQuestionnaire"))
  );
  let questions = currentOperatedQuestionnaire.questions;
  console.log(" currentOperatedQuestionnaire 中的 questions = " + questions);

  let title = document.getElementById("input_questionnaire_title");
  title.value = currentOperatedQuestionnaire.title;
  for (let i = 0; i < questions.length; i++) {
    //刷新时填充对应的数据到题目里
    let type = questions[i].type;
    if (type == "single") {
      let singleDiv = createSingleChoice(); //先创建HTML
      //标题
      let Inputs = singleDiv.getElementsByTagName("input");
      Inputs[0].value = questions[i].description;
      //选项
      let labels = singleDiv.getElementsByTagName("label");
      for (let j = 0; j < labels.length; j++) {
        //再填充
        labels[j].lastChild.value = questions[i].answers[j];
      }
    } else if (type == "multiple") {
      let multipleDiv = createMultipleChoice();
      //标题
      let Inputs = multipleDiv.getElementsByTagName("input");
      Inputs[0].value = questions[i].description;
      //选项
      let labels = multipleDiv.getElementsByTagName("label");
      for (let j = 0; j < labels.length; j++) {
        labels[j].lastChild.value = questions[i].answers[j];
      }
    } else {
      let textDiv = createTextChoice();
      //标题
      let Inputs = textDiv.getElementsByTagName("input");
      Inputs[0].value = questions[i].description;
      //选项（文本框）
      let inputs = textDiv.getElementsByTagName("input");
      inputs[0].value = questions[i].description;
      inputs[1].value = questions[i].answer;
    }
  }
}

//保存问卷作答后的数据,注意：不允许留空
function SaveData_btn() {
  console.log("测试：SaveData_btn() >>");
  //获取当前操作的问卷对象
  Questionnaire = JSON.parse(
    localStorage.getItem("currentOperatedQuestionnaire")
  );

  //获取问卷标题输入框的内容
  let titleInput = document.getElementById("input_questionnaire_title");
  Questionnaire.title = titleInput.value.toString();
  Questionnaire.questions = []; //先清空之前保存的内容（否则出现之前保存的数据会重复保存一遍）

  // 分别对选择题（单选、多选归一类）和文本题进行数据保存处理

  //获取 id="questionnaire_content" 的div -> 所有question (div) -> 所有的label -> input输入框
  let questions = document
    .getElementById("questionnaire_content")
    .getElementsByTagName("div");
  console.log("HTML中 questions[] = " + questions);
  console.log("HTML中 questions[].length = " + questions.length);
  //console.log("questions[0].getAttribute(type) = ", questions[0].getAttribute("type"));
  for (let i = 0; i < questions.length; i++) {
    if (
      questions[i].getAttribute("type") == "single" ||
      questions[i].getAttribute("type") == "multiple"
    ) {
      let selectChoiceQuestion = {
        type: "",
        description: "",
        "must-have": 0, //是否必选
        answers: [], //问题的选项内容
        value: [],
      };

      if (questions[i].getAttribute("type") == "single") {
        selectChoiceQuestion.type = "single";
      } else {
        selectChoiceQuestion.type = "multiple";
      }

      //获取titleInput框中的内容
      //第一个titleInput，其余是“增删查改”input键
      let Inputs = questions[i].getElementsByTagName("input");
      selectChoiceQuestion.description = Inputs[0].value.toString();

      let labels = questions[i].getElementsByTagName("label");

      //单选的每个div总有两个label，双选的有4个,每个label只有两个input，只有第二个是输入框input,获取输入到其中的信息
      for (let j = 0; j < labels.length; j++) {
        let radio = labels[j].firstChild;
        let input_2 = labels[j].lastChild;
        //把input框中的信息进行保存
        if (radio.checked) {
          selectChoiceQuestion.value.push(radio.value);
        }
        selectChoiceQuestion.answers.push(input_2.value.toString());
      }

      Questionnaire.questions.push(selectChoiceQuestion);
    } else {
      let textQuestion = {
        type: "text",
        description: "",
        "must-have": 0,
        answer: "",
      };
      let Inputs = questions[i].getElementsByTagName("input");
      textQuestion.description = Inputs[0].value.toString();
      textQuestion.answer = Inputs[1].value.toString();
      Questionnaire.questions.push(textQuestion);
    }
  }

  localStorage.setItem(
    "currentOperatedQuestionnaire",
    JSON.stringify(Questionnaire)
  );
  //获取当前操作问卷对象在问卷数组（保存于localStorage）中的下标
  let indexOfcurrentOperatedQuestionnaire = parseInt(
    localStorage.getItem("indexOfcurrentOperatedQuestionnaire")
  );
  console.log(
    "遍历HTML后，Questionnaire.questions[] = " + Questionnaire.questions
  );
  console.log(
    "遍历HTML后，Questionnaire.questions[].length = " +
    Questionnaire.questions.length
  );
  console.log(
    "localStorage中的 indexOfcurrentOperatedQuestionnaire =  " +
    JSON.parse(localStorage.getItem("indexOfcurrentOperatedQuestionnaire"))
  );
  console.log(
    "indexOfcurrentOperatedQuestionnaire = " +
    indexOfcurrentOperatedQuestionnaire
  );
  let quesionnaires = JSON.parse(localStorage.getItem("Questionnaires"));
  //更新localStorage中对应位置的的数据
  quesionnaires[indexOfcurrentOperatedQuestionnaire] = Questionnaire;
  console.log(
    "quesionnaires[indexOfcurrentOperatedQuestionnaire] = " +
    quesionnaires[indexOfcurrentOperatedQuestionnaire]
  );
  localStorage.setItem("Questionnaires", JSON.stringify(quesionnaires));

  //测试代码：
  quesionnaires = JSON.parse(localStorage.getItem("Questionnaires"));
  console.log(
    "保存到localStorage的当前操作问卷对象quesionnaires[indexOfcurrentOperatedQuestionnaire]) = ：" +
    quesionnaires[indexOfcurrentOperatedQuestionnaire]
  );
  // saveQuestionnaireBtn();
}

//检查是否留空(ing)
function checkQuestionnaireHasNull() {


  //清空保存的未完整数据

  return true;
}

//“保存问卷”按键(ing)
function saveQuestionnaireBtn() {
  //不检查也可以吧，发布时才要检查
  // if(checkQuestionnaireHasNull()){
  //   alert("不能留空,保存失败");
  //   return ;
  // }
  SaveData_btn();
  alert("数据保存成功，跳转到问卷列表");

  //跳转到总问卷页面前，将当前操作问卷设为空对象
  localStorage.setItem("currentOperatedQuestionnaire", JSON.stringify({}));

  window.location.href = "../html/list.html";
}

//发布问卷按键(ing)
function releaseQuestionnaire() {
  Questionnaire.state = 1;
  //发布成功，跳转到总问卷页面
  //并将当前操作问卷设为空对象
  localStorage.setItem("currentOperatedQuestionnaire", JSON.stringify({}));
}